<?php
/**
 * Created by PhpStorm.
 * User: wangjiangtao
 * Date: 2022/7/14
 * Time: 18:32
 */

namespace App\Modules\Popularize\Platform;


use App\Http\Model\Device;
use App\Http\Model\UserRegisterLog;
use App\Modules\Popularize\Lib\StrLib;

class PlatformFactory
{
    private static $map = [
        'huawei' => 'huawei',
        'xiaomi' => 'xiaomi',
        'oppo' => 'oppo',
    ];
    private static $_instances;

    private function __construct()
    {
    }


    public static function getInstance($data)
    {
        write_log('Platform', 'getInstance ', [$data]);

        $platformInfo = [];
        if (!$data) {
            return null;
        }
        switch ($data) {
            case isset($data['guid']):
                $platformInfo = self::_getPlatformInfoByGuid($data['guid']);
                break;
            case isset($data['user']):
                $platformInfo = self::_getPlatformInfoByUserId($data['user']);
                break;
            case isset($data['device']):
                $platformInfo = self::_getPlatformInfoByDevice($data['device']);
                break;
        }

        list($callback, $platform, $device, $userId) = $platformInfo;
        write_log('Platform', 'platformInfo ', [$platformInfo,$data]);

        //返回的渠道名称，获取渠道实例
        $platformName = self::_getPlatformName($platform);
        if (empty($platformName)) {
            write_log('Platform', 'platform读取失败', [$platformName, $platformInfo]);
            return null;
        }

        if (isset(self::$_instances[$platformName])) {
            return self::$_instances[$platformName];
        }

        $className = __NAMESPACE__ . '\\' . 'Platform' . StrLib::camelize($platformName);
        write_log('Platform', 'className ', $className);

        if (!isset($device->guid) || !class_exists($className)) {
            write_log('Platform', 'ClassNotFound', [$className, $device->guid, $device]);
            return null;
        }
        $instance = new $className($callback, $platform, $device, $userId);
        self::$_instances[$platformName] = $instance;
        return $instance;
    }


    private static function _getPlatformInfoByDevice($params)
    {
        $params = array_merge($params, self::_parse_app_UA(), ['client_ip' => client_ip()]);

        $itemArr = [
            'idfa' => strtolower($params['idfa'] ?? ''),
            'imei' => strtolower($params['imei'] ?? ''),
            'oaid' => strtolower($params['oaid'] ?? ''),
            'vaid' => strtolower($params['vaid'] ?? ''),
            'aaid' => strtolower($params['aaid'] ?? ''),
            'caid1' => strtolower($params['caid1'] ?? ''),
            'caid2' => strtolower($params['caid2'] ?? ''),
            'imeiMD5' => '',
            'idfaMD5' => '',
            'imeidMD5' => '',
            'idfadMD5' => '',
            'ip' => $params['client_ip'],
            'ua_ip_md5' => md5($params['client_ip']),
            'idfaMD5d' => '',
        ];
        if (!empty($itemArr['idfa'])) {
            $itemArr['idfaMD5'] = md5($itemArr['idfa']);
            $itemArr['idfadMD5'] = md5(strtoupper($itemArr['idfa']));
            $itemArr['idfaMD5d'] = strtoupper(md5($itemArr['idfa']));
            $itemArr['idfaMD5u'] = strtoupper(md5(strtoupper($itemArr['idfa'])));
        }

        if (!empty($itemArr['imei'])) {
            $itemArr['imeiMD5'] = md5($itemArr['imei']);
            $itemArr['imeidMD5'] = md5(strtoupper($itemArr['imei']));
        }

        if (!empty($itemArr['oaid'])) {
            $itemArr['oaidlMD5'] = md5(strtolower($itemArr['oaid']));
            $itemArr['oaiduMD5'] = md5(strtoupper($itemArr['oaid']));
        }

        $adfaArr = ['00000000-0000-0000-0000-000000000000', '00000000000000000000000000000000', ''];
        $deviceModel = new Device();
        foreach ($itemArr as $k => $v) {
            if (empty($v) || in_array($v, $adfaArr)) {
                continue;
            }
            $allParam = $deviceModel->getParam($v);
            if (!empty($allParam)) {
                $params = array_merge($params, $allParam);
                break;
            }
        }

        //特殊处理，小米800004没有走到检测链接的，也要走小米
        if (empty($params['platform']) && $params['channel_id'] == 800004) {
            $params['platform'] = $params['channel_id'];
        }

        return [$params['callback'] ?? "", $params['platform'] ?? "", (object)$params, 0];
    }

    private static function _getPlatformInfoByGuid($guid)
    {

        //从device表拿数据
        $deviceInfo = Device::query()->where(['guid' => $guid])->orderByDesc('id')->first();
        //如果设备表里没有，或者oaid、idfa、imei都是空值，直接返回null
        if (!$deviceInfo || (empty($deviceInfo->oaid) && empty($deviceInfo->idfa) && empty($deviceInfo->imei))) {
            write_log('Platform', '_getPlatformInfoByGuid ', ['msg' => '没有找到归因条件', 'guid' => $guid]);
            return [0, 0, null, 0];
        }
        //oaid 是默认空值
        if ($deviceInfo->oaid == '00000000000000000000000000000000' || $deviceInfo->oaid == '00000000-0000-0000-0000-000000000000') {
            $deviceInfo->oaid = '';
        }
        //如果设备都是空的
        if (empty($deviceInfo->oaid) && empty($deviceInfo->idfa) && empty($deviceInfo->imei)) {
            return [0, 0, null, 0];
        }
        //获取回调URL，和渠道号
        $callbackUrl = $deviceInfo->callback ?? "";
        $platform = $deviceInfo->platform ?? "";

        return [$callbackUrl, $platform, $deviceInfo, 0];

    }

    private static function _getPlatformInfoByUserId($userId)
    {
        $userRegisterLog = (new UserRegisterLog())->getUserRegisterLog($userId);
        if (!$userRegisterLog) {
            return [];
        }
        $guid = $userRegisterLog->guid;
        list($callbackUrl, $platform, $deviceInfo, $uid) = self::_getPlatformInfoByGuid($guid);
        return [$callbackUrl, $platform, $deviceInfo, $userId];
    }

    private static function _getPlatformName($platform)
    {
        if(empty($platform)){
            return "";
        }

        //读取poop-an1这类platform
        $platformArr = explode('-', $platform);
        if (isset($platformArr[1])) {
            return $platformArr[0];
        }
        //读取精确platform
        if (isset(self::$map[$platform])) {
            return self::$map[$platform];
        }
        //模糊查询platform，如华为88开头的一些platform
        foreach (self::$map as $key => $value) {
            if (strpos($platform, $key . '') === 0) {
                return $value;
            }
        }
        return $platform;
    }

    /**
     * 从 UA 解析出[软件版本 | APP系统名 | 手机型号 | 渠道商ID]
     * @return array
     */
    protected static function _parse_app_UA()
    {
        $originalUA = [];

        $userAgent = $_SERVER['HTTP_H5_USER_AGENT'] ?? $_SERVER['HTTP_USER_AGENT'] ?? '';
        if (!empty($userAgent)) {
            $originalUA = explode(';', $userAgent);
        }

        return [
            'app' => $originalUA[0] ?? 'kkaudio',
            'version_no' => $originalUA[1] ?? '',
            'os_name' => $originalUA[2] ?? '',
            'device' => $originalUA[4] ?? '',
            'channel_id' => $originalUA[5] ?? '',
            'guid' => $originalUA[6] ?? ''
        ];
    }
}
